package com.power.leopard.common.util;

import java.util.List;

import org.apache.commons.lang3.ClassUtils;

import com.power.leopard.config.ConfigManager;
import com.power.leopard.constants.Constants;
import com.power.leopard.extension.ExtensionLoader;

public class ServiceConfigUtil {

	private static String interfacePackageConfig = ExtensionLoader.getInstance(ConfigManager.class).get("leopard.interface-package", "com.power");
	private static String[] interfacePackages = { "com.power" };

	static {
		interfacePackages = (interfacePackageConfig == null || interfacePackages.length == 0) ? interfacePackages : (Constants.CommaSplitPattern
				.split(interfacePackageConfig));
	}

	public static Class<?> getServiceInterface(Class<?> type) {
		Class<?>[] interfaces = type.getInterfaces();
		Class<?> interfaceClass = null;
		if (interfaces != null && interfaces.length > 0) {
			interfaceClass = interfaces[0];
		} else {
			List<Class<?>> allInterfaces = ClassUtils.getAllInterfaces(type);
			if (allInterfaces != null && !allInterfaces.isEmpty()) {
				for (Class<?> i : allInterfaces) {
					if (isValidType(i)) {
						interfaceClass = i;
						break;
					}
				}

				if (interfaceClass == null) {
					interfaceClass = allInterfaces.get(0);
				}
			}

			if (interfaceClass == null) {
				interfaceClass = type;
			}
		}
		return interfaceClass;
	}

	private static boolean isValidType(Class<?> clazz) {
		String name = clazz.getName();
		for (String interfacePackage : interfacePackages) {
			if (name.startsWith(interfacePackage)) {
				return true;
			}
		}
		return false;
	}
}
